import {PageContainer} from "@ant-design/pro-layout";
import type {ProColumns, ActionType} from "@ant-design/pro-table";
import ProTable from '@ant-design/pro-table';
import {accounts} from "@/services/abis/account";
import {Button, Col, Form, Popconfirm, Row, Upload} from "antd";
import {LoadingOutlined, PlusOutlined} from "@ant-design/icons";
import type {ProFormInstance} from "@ant-design/pro-form";
import {ModalForm, ProFormText} from "@ant-design/pro-form";
import {useRef, useState} from "react";
import {StatusEnum} from "@/services/abis/enum";
import {green, orange, red} from "@ant-design/colors";
import ImgCrop from "antd-img-crop";
import type {UploadChangeParam} from "antd/es/upload";
import type {UploadFile} from "antd/es/upload/interface";
import styles from './index.module.less'

const addCount = (values: ABIS.Account) => {
  console.log(values)
}

export default () => {
  const [modalVisit, setModalVisit] = useState<boolean>(false)
  const [isEdit, setIsEdit] = useState<boolean>(false)
  const ref = useRef<ActionType>()
  const formRef = useRef<ProFormInstance>()
  const [avatarImg, setAvatarImg] = useState<UploadFile[]>([])
  const [loading, setLoading] = useState<boolean>(false)
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined/> : <PlusOutlined/>}
      <div style={{marginTop: 8}}>上传头像</div>
    </div>
  )

  const columns: ProColumns<ABIS.AccountVO>[] = [
    {
      title: '序号',
      dataIndex: 'id',
      valueType: 'index'
    },
    {
      title: '账号',
      dataIndex: 'account',
      order: 6
    },
    {
      title: '昵称',
      dataIndex: 'username',
      order: 5
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: StatusEnum,
      filters: true,
      onFilter: false,
      search: false
    },
    {
      title: '创建人',
      dataIndex: 'created_by_name',
      order: 4,
      render: (value, record) => {
        return record.created_by === 0 ? '系统' : value
      }
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      order: 2,
      sorter: true,
      search: {
        transform: value => {
          return {
            created_start_at: value[0] || null,
            created_end_at: value[1] || null
          }
        }
      },
      render: (_, record) => {
        return record.created_at.replace('T', ' ')
      }
    },
    {
      title: '更新人',
      dataIndex: 'updated_by_name',
      order: 3,
      render: (value, record) => {
        return record.updated_by === 0 ? '系统' : value
      }
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      valueType: 'dateTimeRange',
      order: 1,
      sorter: true,
      search: {
        transform: value => {
          return {
            updated_start_at: value[0] || null,
            updated_end_at: value[1] || null
          }
        }
      },
      render: (_, record) => {
        return record.updated_at ? record.updated_at.replace('T', '') : '-'
      }
    },
    {
      title: '操作',
      valueType: "option",
      width: 160,
      render: (_, record) => record.account !== 'admin' && [
        <a key="edit" onClick={() => {
          setIsEdit(true)
          // setModalVisit(true)
          // formRef.current?.setFieldsValue(record)
        }}>编辑</a>,
        record.status === 1 ?
          <a key="disable" style={{color: orange.primary}} onClick={() => {
            // batchStatus([record.id])
          }}>禁用</a> :
          <a key="enable" style={{color: green.primary}} onClick={() => {
            // batchStatus([record.id], 1)
          }}>启用</a>,
        <Popconfirm
          key="delete"
          title="您确认要删除?删除后不可恢复"
          onConfirm={() => {
            // batchDelete([record.id])
          }}
        >
          <a style={{color: red.primary}}>删除</a>
        </Popconfirm>
      ]
    }
  ]

  const changeAvatarImg = (info: UploadChangeParam<UploadFile>) => {
    console.log('info', info)
  }

  return (
    <>
      <PageContainer>
        <ProTable<ABIS.AccountVO>
          cardBordered={true}
          columns={columns}
          rowKey={record => record.id}
          actionRef={ref}
          rowSelection={{
            preserveSelectedRowKeys: true,
            getCheckboxProps: record => {
              const disabled = record.account === 'admin'
              return {disabled: disabled}
            }
          }}
          request={async (params, sort, filter) => {
            console.log('params', params)
            console.log('sort', sort)
            console.log('filter', filter)
            const msg = await accounts({...params, ...sort, ...(filter.status ? filter : {})})
            return {
              data: msg.data.list,
              success: msg.code == 1000,
              total: msg.data.total
            }
          }}
          toolbar={{
            actions: [
              <Button type="primary" icon={<PlusOutlined/>} onClick={() => {
                setModalVisit(true)
                setIsEdit(false)
              }}>新建角色</Button>,
              <ModalForm<ABIS.Account>
                title={isEdit ? '编辑账号' : '添加新账号'}
                formRef={formRef}
                autoFocusFirstInput
                isKeyPressSubmit
                visible={modalVisit}
                modalProps={{
                  destroyOnClose: true,
                }}
                onFinish={async (values) => {
                  addCount(values)
                  return true
                }}
                onVisibleChange={visible => {
                  if (!visible) {
                    setModalVisit(false)
                  }
                }}
              >
                <Row>
                  <Col span={12}>
                    <ProFormText name={"account"} label={"账号"} placeholder={"请输入账号"} required={true}/>
                    <ProFormText name={"username"} label={"昵称"} placeholder={"请输入昵称"}/>
                  </Col>
                  <Col span={12} style={{display: 'inline-flex', justifyContent: 'center', alignItems: 'flex-end'}}>
                    <Form.Item style={{marginBottom: 0}}>
                      <ImgCrop>
                        <Upload
                          className={styles.avatarUpload}
                          name="files"
                          maxCount={1}
                          listType="picture-card"
                          showUploadList={false}
                          onChange={(info => changeAvatarImg(info))}
                        >
                          {/*{avatarImg ? <img src={avatarImg.toString()} alt="avatar"/> : uploadButton }*/}
                          {uploadButton}
                        </Upload>
                      </ImgCrop>
                    </Form.Item>
                    {/*<ImgCrop>*/}
                    {/*  <ProFormUploadDragger*/}
                    {/*    fieldProps={{*/}
                    {/*      listType: 'picture-card',*/}
                    {/*      showUploadList:false,*/}
                    {/*      fileList: avatarImg*/}
                    {/*    }}*/}
                    {/*    onChange={ data => changeAvatarImg(data)}*/}
                    {/*    width="sm"*/}
                    {/*    name="avatar"*/}
                    {/*    max={1}*/}
                    {/*    value={avatarImg}*/}
                    {/*    title={false}*/}
                    {/*    description="上传头像"*/}
                    {/*  >*/}
                    {/*  </ProFormUploadDragger>*/}
                    {/*</ImgCrop>*/}
                  </Col>
                </Row>
                <ProFormText.Password name={"password"} label={"密码"} placeholder={"请输入密码"} required={true}/>
                <ProFormText.Password name={"password_confirm"} label={"确认密码"} placeholder={"请确认密码"} required={true}/>
              </ModalForm>
            ]
          }}
          pagination={{
            hideOnSinglePage: true
          }}
        />
      </PageContainer>
    </>
  )
}
